#-*-coding: utf8 -*-
import os
import stat
import time
from collections import namedtuple

from django.views.generic.base import TemplateView
from django.utils.translation import gettext_lazy as _
from django.urls import reverse
from django.core.urlresolvers import Resolver404
from django.http import HttpResponse
from django.contrib.auth.mixins import LoginRequiredMixin

from blog.settings import FTP_PATH


class FTPView(LoginRequiredMixin, TemplateView):

    template_name = 'ftp.html'
    file_obj = namedtuple('file_obj', ['name', 'type', 'size', 'create_time', 'path'])

    def get_file_info(self, abs_path, path):
        try:
            files = os.listdir(abs_path)
        except OSError:
            raise Resolver404
        os.chdir(abs_path)
        for i, f in enumerate(files):
            st = os.stat(f)
            if stat.S_ISREG(st.st_mode):
                t = 'f'
            elif stat.S_ISDIR(st.st_mode):
                t = 'd'
            else:
                t = 'o'
            units = ('B', 'K', 'M', 'G')
            size = st.st_size
            n = 0
            u = units[n]
            while size >= 1024.0 and u != 'G':
                size /= 1024.0
                n += 1
                u = units[n]
            files[i] = self.file_obj(f, t, '{}{}'.format(round(size, 2), u),
                                     time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(st.st_mtime)),
                                     os.path.join(path, f))
        return files

    def get_relative_path(self, req_path):
        main_path = reverse('admin_ftp', kwargs={'path': ''})
        if req_path.startswith(main_path):
            path = req_path[len(main_path):]
        else:
            path = ''
        return path

    def get_context_data(self, **kwargs):
        context = super(FTPView, self).get_context_data()
        path = self.request.path
        path = self.get_relative_path(path)
        pathes = [_('main')]
        if path:
            pathes += path.split('/')
        relat_path = ''
        for i, p in enumerate(pathes):
            if i > 0 and p:
                relat_path += p + '/'
            pathes[i] = {'path': relat_path, 'name': p}
        abs_path = os.path.join(FTP_PATH, path)
        files = self.get_file_info(abs_path, path)
        context['files'] = files
        context['path'] = pathes
        return context
    
    def post(self, request, **kwargs):
        files = request.FILES
        path = self.get_relative_path(request.path)
        abs_path = os.path.join(FTP_PATH, path)
        for f in files.getlist('file'):
            file_path = os.path.join(abs_path, f.name)
            with open(file_path, 'wb') as fb:
                for chunk in f.chunks():
                    fb.write(chunk)
        return HttpResponse(content='ok')
